package com.nav.backend.controller;

import com.nav.backend.pojo.DTO.UpdateUserDTO;
import com.nav.backend.pojo.DTO.UserAddressDTO;
import com.nav.backend.pojo.User;
import com.nav.backend.pojo.UserAddress;
import com.nav.backend.service.UserService;
import com.nav.backend.utils.JWTUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * UserController 用户控制器类，处理与用户相关的请求
 *
 * @author Seamher
 */
@Validated
@RestController
@RequestMapping("/user")
public class UserController {

    private final UserService userService;

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    public UserController(UserService userService) {
        this.userService = userService;
    }

    /**
     * 用户注册
     *
     * @param User 登录用户
     * @return 登录结果
     */
    @PostMapping(value = "/register")
    public ResponseEntity<String> register(@RequestBody User User) {
        String account = User.getAccount();
        String password = User.getPassword();
        logger.info("Register request received for account: {}", account);

        // 验证用户名是否重复
        User user = userService.findByUserName(account);

        // 注册
        if (user == null) {
            userService.register(account, password);
            logger.info("User registered successfully: {}", account);
            return ResponseEntity.ok("");
        } else {
            logger.warn("Registration attempt failed. Account already exists: {}", account);
            return ResponseEntity.status(406).body("");
        }
    }

    /**
     * 用户登录
     *
     * @param loginData 登录信息
     * @return 登录结果
     */
    @PostMapping(value = "/login")
    public ResponseEntity<String> login(@RequestBody Map<String, String> loginData) {
        String account = loginData.get("account");
        String password = loginData.get("password");
        logger.info("Login attempt for account: {}", account);

        // 验证用户是否存在
        User user = userService.findByUserName(account);
        if (user == null) {
            logger.warn("Login failed. User not found: {}", account);
            return ResponseEntity.status(407).body(""); // 用户不存在
        } else {

            // 验证密码是否正确
            if (Objects.equals(password, user.getPassword())) {
                Map<String, Object> claims = new HashMap<>();
                claims.put("account", account);
                logger.info("User logged in successfully: {}", account);
                var token = JWTUtils.genToken(claims);
                logger.warn("User token: {}", token);
                return ResponseEntity.ok(token);
            } else {
                logger.warn("Login failed. Incorrect password for account: {}", account);
                return ResponseEntity.status(408).body(""); // 密码错误
            }
        }
    }

    /**
     * 用户注销
     *
     * @param account 账户名
     * @param password 密码
     * @return 注销结果
     */
    @DeleteMapping("/logout")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public ResponseEntity<String> logout(@RequestParam String account, @RequestParam String password) {
        User user = userService.findByUserName(account);
        if (Objects.equals(password, user.getPassword())) {
            userService.logoutUserAddress(account);
            userService.logoutCollectionAddress(account);
            userService.logoutCollectionPath(account);
            userService.logoutRingSearch(account);
            userService.logoutTreeLineSearch(account);
            userService.logoutTwoPointsSearch(account);
            userService.logout(account);
            return ResponseEntity.noContent().build();
        } else {
            return ResponseEntity.status(408).body(""); // 密码错误
        }
    }

    /**
     * 用户信息修改
     *
     * @param updateUserDTO 用户信息
     * @return 用户信息修改结果
     */
    @PutMapping("/modifyInfo")
    public ResponseEntity<String> modifyInfo(@RequestBody UpdateUserDTO updateUserDTO) {
        String account = updateUserDTO.getAccount();
        String password = updateUserDTO.getPassword();
        String phone = updateUserDTO.getPhone();
        String email = updateUserDTO.getEmail();
        String newAccount = updateUserDTO.getNew_account();
        logger.info("Modify info request received for account: {}", account);

        User user = userService.findByUserName(account);
        if (userService.findByUserName(newAccount) != null && !Objects.equals(account, newAccount)) {
            logger.warn("Modify info failed. New account already exists: {}", newAccount);
            return ResponseEntity.status(406).body(""); // 用户名重复
        } else if (userService.findByEmail(email) != null && !Objects.equals(email, user.getEmail())) {
            logger.warn("Modify info failed. Email already exists: {}", email);
            return ResponseEntity.status(411).body(""); // 邮箱重复
        } else if (userService.findByPhone(phone) != null && !Objects.equals(phone, user.getPhone())) {
            logger.warn("Modify info failed. Phone already exists: {}", phone);
            return ResponseEntity.status(412).body(""); // 电话重复
        } else {
            userService.modifyInfo(account, password, phone, email, newAccount);
            logger.info("User info modified successfully for account: {}", account);
            return ResponseEntity.ok("");
        }
    }

    /**
     * 获取用户信息
     *
     * @param account 用户名
     * @return 获取用户信息结果
     */
    @GetMapping("/info")
    public User info(@RequestParam String account) {
        logger.info("Info request received for account: {}", account);
        return userService.findByUserName(account);
    }

    /**
     * 增加用户常用地址
     *
     * @param userAddress 用户常用地址信息
     * @return 增加用户常用地址结果
     */
    @PostMapping("/addAddress")
    public ResponseEntity<String> addAddress(@RequestBody UserAddress userAddress) {
        String user_comment = userAddress.getUser_comment();
        String user_address = userAddress.getUser_address();
        Double user_address_x = userAddress.getUser_address_x();
        Double user_address_y = userAddress.getUser_address_y();
        String user_address_info = userAddress.getUser_address_info();
        String account = userAddress.getAccount();
        logger.info("Add address request received for account: {}", account);

        userService.addAddress(user_comment, user_address, user_address_x, user_address_y, user_address_info, account);
        logger.info("Address added successfully for account: {}", account);
        return ResponseEntity.ok("");
    }

    /**
     * 获取用户常用地址
     *
     * @param account 用户名
     * @return 获取用户常用地址结果
     */
    @GetMapping("/address")
    public ResponseEntity<UserAddressDTO> getAddress(@RequestParam String account) {
        logger.info("Get address request received for account: {}", account);

        List<UserAddress> addresses = userService.getAddress(account);
        UserAddressDTO userAddressDTO = new UserAddressDTO(addresses);
        logger.info("Address retrieved successfully for account: {}", account);
        return ResponseEntity.ok(userAddressDTO);
    }

    /**
     * 修改用户常用地址
     *
     * @param userAddress 用户常用地址信息
     * @return 修改用户常用地址结果
     */
    @PutMapping("/modifyAddress")
    public ResponseEntity<String> modifyAddress(@RequestBody UserAddress userAddress) {
        Integer user_address_id = userAddress.getUser_address_id();
        String user_comment = userAddress.getUser_comment();
        String user_address = userAddress.getUser_address();
        Double user_address_x = userAddress.getUser_address_x();
        Double user_address_y = userAddress.getUser_address_y();
        String user_address_info = userAddress.getUser_address_info();
        logger.info("Modify address request received for address ID: {}", user_address_id);

        userService.modifyAddress(user_comment, user_address, user_address_x, user_address_y, user_address_info, user_address_id);
        logger.info("Address modified successfully for address ID: {}", user_address_id);
        return ResponseEntity.ok("");
    }

    /**
     * 删除用户常用地址
     *
     * @param userAddress 用户常用地址信息
     * @return 删除用户常用地址结果
     */
    @DeleteMapping("/deleteAddress")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public ResponseEntity<String> deleteAddress(@RequestBody UserAddress userAddress) {
        Integer user_address_id = userAddress.getUser_address_id();
        logger.info("Delete address request received for address ID: {}", user_address_id);

        userService.deleteAddress(user_address_id);
        logger.info("Address deleted successfully for address ID: {}", user_address_id);
        return ResponseEntity.noContent().build();
    }
}
